package com.hunttown.mes.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * created by hunttown on 2017/7/27
 */
public class XMLUtils {
    private static final XmlMapper XML_MAPPER = new XmlMapper();

    public static <T> T unmashal(String xml, String encoding, Class<T> cls) throws IOException {
        if (StringUtils.isBlank(xml) || StringUtils.isBlank(encoding)) {
            throw new RuntimeException("unmashal xml function's param xml and encoding cannt be null!");
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(encoding));
        T obj = XML_MAPPER.readValue(bais, cls);
        return obj;
    }

    public static <T> String marshal(T bean) throws JsonProcessingException {
        if (bean == null) {
            throw new RuntimeException("mashal bean function's param bean cannt be null!");
        }
        String string = XML_MAPPER.writeValueAsString(bean);
        return string;
    }
}
